# -*- coding: utf-8 -*-

from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
from django.forms.models import modelformset_factory
from models import *
from django.shortcuts import render_to_response,render
from django.template import RequestContext
from forms import PurchaseRequestForm_add,PurchaseRequestItemForm
from django.http import HttpResponseRedirect, Http404
import math,logging
from django.views.decorators.cache import cache_page

current_app = 'warehouse_pr'
current_url = '/erp/pr/'
title = '采购申请'

@login_required()#login_url='/'
def home(request):
    return TemplateResponse(request,'warehouse/index.html',{'app':'warehouse'}
                            )

#@cache_page(60 * 1) 
@login_required()
def pr_list(request,page=1):   
    #pr_choice = list(PR_STATUS_CHOICES)  
    #logging.error(pr_choice)
    return render_to_response("warehouse/common/list.html",
                              {'app':current_app,'current_url':current_url,
                               'title':title,'back_url':current_url ,
                               'dojo':True,
                               #'pr_choice': pr_choice,                             
                               }
                              ,context_instance=RequestContext(request))
@login_required()
def pr_log(request,pr_id):
    p_r = PurchaseRequest.objects.get(pk=pr_id)
    return render_to_response("warehouse/log.html",
                              {'app':current_app,'current_url':current_url,
                               'back_url':current_url+str(pr_id),
                               'title':title,
                               'op_items':p_r.GetOperatorLog()
                               }
                              ,context_instance=RequestContext(request))
@login_required()
def pr_detail(request,pr_id):
    obj = PurchaseRequest.objects.get(pk=pr_id)
    obj.user = request.user
    form = None
    if request.method == 'POST':
        form = PurchaseRequestForm_add(request.POST,instance=obj) 
        if form.is_valid(): 
            form.save(True)
    else:        
        form = PurchaseRequestForm_add(instance=obj) 
        pass
    
    if obj.Can_Edit==False:
        #'PR_Use', 'PR_Adult_User','PR_Customer','PR_Project','PR_Description'
        form.fields['PR_Use'].widget.attrs['readonly'] = True
        form.fields['PR_Adult_User'].widget.attrs['readonly'] = True
        form.fields['PR_Customer'].widget.attrs['readonly'] = True
        form.fields['PR_Project'].widget.attrs['readonly'] = True
        form.fields['PR_Description'].widget.attrs['readonly'] = True

    
    return render_to_response("warehouse/common/detail.html",
                              {'app':current_app,'current_url':current_url,
                               'title':title,'back_url':current_url ,
                               'form':form, 
                               'id':pr_id, 
                               'obj':obj,
                               }
                              ,context_instance=RequestContext(request))

@login_required()
def pr_do(request,pr_id,do):
    p_r = PurchaseRequest.objects.get(pk=pr_id)
    p_r.user = request.user
    p_r.Do(request.user,do)
    return HttpResponseRedirect(current_url+pr_id)

@login_required()
def pr_add(request):
    if request.method == 'POST': # If the form has been submitted...
        form = PurchaseRequestForm_add(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            pr_new = form.save(commit=False)
            #pr_new.PR_Apply_User = User.Employee_set.all()[0]#  Employee.GetEmployeeFromUser(User)
            pr_new.PR_Apply_User = Employee.objects.get(Emp_User__username__exact=request.user.username)
             
            pr_new.save()
            return HttpResponseRedirect(current_url) # Redirect after POST
    else:
        form = PurchaseRequestForm_add() # An unbound form
        
    return render_to_response("warehouse/common/dialog.html",
                              {'app':current_app,'current_url':current_url,
                               'form':form,'back_url':current_url ,
                               'post_url':current_url+'add',
                               'form_title':'新增采购申请',
                               'form_help':'',
                               #'dojo':'1',
                               }
                              ,context_instance=RequestContext(request))
    
    
@login_required()
def pr_item_del(request,pr_id,pri_id):
    pri = PurchaseRequestItems.objects.get(id=pri_id)
    pri.delete()
    return HttpResponseRedirect(current_url+pr_id)

@login_required()
def pr_item_add_edit(request,pr_id,pri_id=0):
    if request.method == 'POST': # If the form has been submitted...
        if (pri_id==0):#add
            form = PurchaseRequestItemForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass           
                
                pr_new = form.save(commit=False)
                pr_new.PRI_PurchaseRequest = PurchaseRequest.objects.get(id=pr_id)             
                pr_new.save()
    
                return HttpResponseRedirect(current_url+pr_id) # Redirect after POST
        else: #edit
            pri = PurchaseRequestItems.objects.get(id=pri_id)
            form = PurchaseRequestItemForm(request.POST,instance=pri) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass           
                form.save(commit=True)
                #pr_new = form.save(commit=False)
                #pr_new.PRI_PurchaseRequest = PurchaseRequest.objects.get(id=pr_id)             
                #pr_new.save()
    
                return HttpResponseRedirect(current_url+pr_id) # Redirect after POST
    else:
        if (pri_id==0):
            form = PurchaseRequestItemForm() # An unbound form
        else:
            pri = PurchaseRequestItems.objects.get(id=pri_id)
            form = PurchaseRequestItemForm(instance=pri) # An unbound form
        
    return render_to_response("warehouse/common/dialog.html",
                              {'app':current_app,'current_url':current_url,
                               'form':form,'back_url':current_url+str(pr_id),
                               'post_url':current_url+pr_id+'/add',
                               'form_title':'新增采购申请条目',
                               'form_help':''
                                }
                              ,context_instance=RequestContext(request))
    

def manage_PurchaseRequest(request):
    PurchaseRequestFormSet = modelformset_factory(PurchaseRequest)
    if request.method == 'POST':
        formset = PurchaseRequestFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            # do something.
    else:
        formset = PurchaseRequestFormSet()
    return render_to_response("warehouse/manage_purchaserequest.html", {
        "formset": formset,
    },context_instance=RequestContext(request))